package com.xiaozhengkeji.mcverifyplus.api;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;
import com.xiaozhengkeji.mcverifyplus.pojo.ResponseBean;
import com.xiaozhengkeji.mcverifyplus.pojo.type.ResCodeType;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import wiki.xsx.core.util.RedisUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/web/open")
public class OpenApi {
    /**
     * 生成验证码
     */
    @GetMapping("GenerateVerificationCode")
    public void GenerateVerificationCode(@ApiParam("当前毫秒的时间戳 例:1630231441052") @RequestParam("date") String date,
                                         HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 50);
        /*将此tap的正确验证码写入Redis,并设置60秒缓存*/
        RedisUtil.getStringHandler(20).set("GVC_" + date, lineCaptcha.getCode(), 60, TimeUnit.SECONDS);
        lineCaptcha.write(response.getOutputStream());
        response.getOutputStream().close();
    }

    /**
     * 验证签名
     */
    @PostMapping("verifySignature")
    public ResponseBean verifySignature(@RequestParam("dateBase64") String dateBase64,
                                        @RequestParam("signed") String signed) {
        return new ResponseBean(ResCodeType.Success, "ok", ResponseBean.verifySignature(Base64.decodeStr(dateBase64), signed), null);
    }
}
